package com.example.demo.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.Mapper.HabitedTaskMapper;
import com.example.demo.Pojo.HabitedTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@RestController
@RequestMapping("/hTask")
public class HabitedTaskController {

    @Autowired
    HabitedTaskMapper habitedTaskMapper;

    @RequestMapping("/addHTask")    //添加Habited_task，参数：HTask实体
    public int addHTask(HttpServletRequest request){
        JSONObject hTask = JSONObject.parseObject(request.getParameter("hTask"));
        HabitedTask t = JSONObject.toJavaObject(hTask, HabitedTask.class);
        int insert = habitedTaskMapper.insert(t);
        return insert;
    }

    @RequestMapping("/allHTask")    //查找所有HTask，参数：userId
    public String allHTask(HttpServletRequest request){
        QueryWrapper<HabitedTask> wrapper = new QueryWrapper<>();
        wrapper.eq("userId",Long.parseLong(request.getParameter("userId")));
        List<HabitedTask> habitedTasks = habitedTaskMapper.selectList(wrapper);
        return JSON.toJSONString(habitedTasks);
    }

//    @RequestMapping("/getHTaskByDate")    //根据日期查找，参数：日期
//    public String getHTaskByDate(HttpServletRequest request) throws ParseException {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        Calendar cd = Calendar.getInstance();
//        cd.setTime(sdf.parse(request.getParameter("date")));
//        QueryWrapper<HabitedTask> wrapper = new QueryWrapper<>();
//        wrapper.ge("taskGmtStart",sdf.format(cd.getTime()).toString());
//        wrapper.le("taskGmtOver",sdf.format(cd.getTime()).toString());
//    }

    @RequestMapping("/toUpdateHTask")    //前往更新页面，参数：hTaskId
    public String toUpdateHTask(HttpServletRequest request){
        HabitedTask habitedTask = habitedTaskMapper.selectById(request.getParameter("hTaskId"));
        return JSON.toJSONString(habitedTask);
    }

    @RequestMapping("/updateHTask")    //更新操作，参数：hTask 实体
    public int updateHTask(HttpServletRequest request){
        JSONObject hTask = JSONObject.parseObject(request.getParameter("hTask"));
        HabitedTask habitedTask = JSONObject.toJavaObject(hTask, HabitedTask.class);
        int i = habitedTaskMapper.updateById(habitedTask);
        return i;
    }

    @RequestMapping("/delHTask")    //逻辑删除，参数：hTaskId
    public int delHTask(HttpServletRequest request){
        int hTaskId = habitedTaskMapper.deleteById(Integer.parseInt(request.getParameter("hTaskId")));
        return hTaskId;
    }
}
